﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Web;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Webdiyer.AspNetCore;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageCommon
{
    public class PageCommon_Pager : ControlBase
    {
        internal int _currentIndex = 1;
        private int _totalCount = 0;
        internal int _pageSize = 0;
        //private Webdiyer.WebControls.Mvc.HtmlPager _pager=null;
        //private static PagerOptions _options = null;
        //private PagerOptions _currentOptions = null;
        private bool _isAjax = false;
        private string _actionUrl = "";
        private string _updateElementID = "";
        private string _forID = "";
        private string _placeholder = "页码";
        private (string key, string value)[] _extraArgs = null;
        private string _pageIndexParameterName = "";
        private bool _showFirstLast = true;
        private bool _showInputBox = true;

        static PageCommon_Pager()
        {
            //_options = new PagerOptions
            //{
            //    PageIndexParameterName = "pageindex",
            //    TagName = "ul",
            //    CssClass = "pagination pull-right",
            //    CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
            //    DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
            //    PagerItemTemplate = "<li>{0}</li>",
            //    HorizontalAlign = "right",
            //    ShowFirstLast = false,
            //    PrevPageText = "<",
            //    NextPageText = ">",
            //    FirstPageText = "|<",
            //    LastPageText = ">|",
            //    NumericPagerItemCount = 5,
            //    AutoHide = true,
            //    //NavigationPagerItemTemplate = "<li ><input type=\"number\" placeholder=\"页码\" class=\"form-control pagerinput\"/></li>"
            //    //Id = "bootstrappager"
            //};


        }

        public PageCommon_Pager PageIndexParameterName(string name)
        {
            _pageIndexParameterName = name;

            return this;
        }

        public PageCommon_Pager(ViewContext viewContext) : base(viewContext)
        {
            //_currentOptions = clone();
        }

        public PageCommon_Pager Source<T>(VM_PagedList<T> lst)
        {
            _currentIndex = lst.PageIndex;
            _totalCount = lst.TotalCount;
            _pageSize = lst.PageSize;

            return this;
        }

        public PageCommon_Pager RecordCount(int totalRecordCount)
        {
            _totalCount = totalRecordCount;

            return this;
        }

        public PageCommon_Pager PageSize(int pageSize)
        {
            _pageSize = pageSize;

            return this;
        }

        public PageCommon_Pager BoxPlaceholder(string placeholder)
        {
            _placeholder = placeholder;

            return this;
        }

        public PageCommon_Pager CurrentIndex(int pageIndex)
        {
            _currentIndex = pageIndex;

            return this;
        }

        public PageCommon_Pager ShowFirstLast(bool isShow = true)
        {
            _showFirstLast = isShow;

            return this;
        }

        public PageCommon_Pager ShowPagerBox(bool isShow)
        {
            //_currentOptions.ShowNumericPagerItems = isShow;
            _showInputBox = isShow;

            return this;
        }


        /// <summary>
        /// 使用异步分页功能
        /// </summary>
        /// <param name="elementID">ajax获取数据后,替换那个元素,必须是id</param>
        /// <param name="actionUrl">获取数据的链接,将会自动根据pagekey替换分页页码,如果该值为空,则使用pager控件生成的url进行获取整页数据,并只替换部分html</param>
        /// <returns></returns>
        public PageCommon_Pager UpdateElementID(string elementID, string actionUrl = "")
        {
            if (!string.IsNullOrWhiteSpace(elementID))
            {
                _updateElementID = elementID;
                _actionUrl = actionUrl.ToStringEx();
                _isAjax = true;

            }
           

            return this;
        }

        public PageCommon_Pager ForControlID(string id)
        {
            _forID = id;

            return this;
        }

        /// <summary>
        /// 用于向分页链接中,增加额外的参数,如tab的id之类的
        /// </summary>
        /// <param name="args">参数列表</param>
        /// <returns></returns>
        public PageCommon_Pager WithExtraArgs(params (string key, string value)[] args)
        {
            _extraArgs = args;
            return this;
        }

        public override HtmlString Render()
        {
            //var str = Html.Pager(_totalCount, _pageSize, _currentIndex, _options).ToHtmlString();
            //ViewContext.Writer.WriteLine("sss");

            var opt = new PagerOptions
            {
                PageIndexParameterName = _pageIndexParameterName.IfEmptyOrWhileSpace("pageindex") ,
                TagName = "ul",
                CssClass = "pagination pull-right",
                CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
                DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
                PagerItemTemplate = "<li>{0}</li>",
                HorizontalAlign = "right",
                ShowFirstLast = _showFirstLast,
                PrevPageText = "<",
                NextPageText = ">",
                FirstPageText = "|<",
                LastPageText = ">|",
                NumericPagerItemCount = 5,
                AutoHide = true,
                ShowNumericPagerItems = _showInputBox,
                //NavigationPagerItemTemplate = "<li ><input type=\"number\" placeholder=\"页码\" class=\"form-control pagerinput\"/></li>"
                //Id = "bootstrappager"
            }; ;

            var htmlAttr= new Dictionary<string, object>();

            if (_isAjax && !string.IsNullOrWhiteSpace(_updateElementID))
            {
                htmlAttr.Add("data-isajax", "true");
                htmlAttr.Add("data-updateelementid", _updateElementID);
                htmlAttr.Add("data-actionurl", _actionUrl);
                opt.CssClass += " ajaxpager";
            }

            if (_extraArgs.HasData())
            {
                var s=_extraArgs.Select(x => $"{x.key}={HttpUtility.UrlEncode(x.value)}").JoinToString('&');
                htmlAttr.Add("data-extraargs",s);
            }

            htmlAttr.AddOrUpdate("data-forid",_forID);

            //if (_placeholder!="页码")
            //{
            //    _currentOptions.NavigationPagerItemTemplate =
            //        _currentOptions.NavigationPagerItemTemplate.Replace("页码", _placeholder);
            //}

            var pageIndexBox = $"<div class=\"pull-right pageIndexBox\"><input type=\"number\" placeholder=\"{_placeholder}\" class=\"form-control pagerinput\"/></div>";
            if (_totalCount <= 0 || _pageSize <= 0 || _totalCount <= _pageSize || Math.Ceiling(_totalCount * 1.0 / _pageSize) < _currentIndex)
            {
                pageIndexBox = "";
            }

            opt.HtmlAttributes = htmlAttr;

            var pager = new HtmlPager(Html, _totalCount, _pageSize, _currentIndex, opt);
            
            using (var writer=new StringWriter())
            {
                pager.WriteTo(writer,HtmlEncoder.Default);

                return new HtmlString(pageIndexBox + writer.ToStringEx());
            }

            //var str = _pager.ToHtmlString();
            // ViewContext.Writer.Write(str);
            //ViewContext.Writer.WriteLine(_pager.ToHtmlString());
            // return MvcHtmlString.Empty;
            
        }



        //private PagerOptions clone()
        //{
        //    /*
        //     *new PagerOptions
        //    {
        //        PageIndexParameterName = "pageindex",
        //        ContainerTagName = "ul",
        //        CssClass = "pagination pull-right",
        //        CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
        //        DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
        //        PagerItemTemplate = "<li>{0}</li>",
        //        HorizontalAlign = "right",
        //        ShowFirstLast = false,
        //        PrevPageText = "<",
        //        NextPageText = ">",
        //        NumericPagerItemCount = 5
                
        //        //Id = "bootstrappager"
        //    };
        //     *
        //     */

        //    return new PagerOptions()
        //    {
        //        PageIndexParameterName = _options.PageIndexParameterName,
        //        TagName = _options.TagName,
        //        CssClass = _options.CssClass,
        //        CurrentPagerItemTemplate = _options.CurrentPagerItemTemplate,
        //        DisabledPagerItemTemplate = _options.DisabledPagerItemTemplate,
        //        PagerItemTemplate = _options.PagerItemTemplate,
        //        HorizontalAlign = _options.HorizontalAlign,
        //        ShowFirstLast = _options.ShowFirstLast,
        //        PrevPageText = _options.PrevPageText,
        //        NextPageText = _options.NextPageText,
        //        FirstPageText = _options.FirstPageText,
        //        LastPageText = _options.LastPageText,
        //        NumericPagerItemCount = _options.NumericPagerItemCount,
        //        AutoHide = _options.AutoHide,
        //        NavigationPagerItemTemplate= _options.NavigationPagerItemTemplate
        //    };
        //}
    }
}
